package band.wukong.practice.springboot.spring4.mvc;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author wukong(wukonggg@139.com)
 */
@RestController
@RequestMapping("/hi")
public class HiRestController {

    private static final Logger logger = LoggerFactory.getLogger(HiRestController.class);

    @RequestMapping(value = "/getJson", produces = {"application/json;charset=UTF-8"})
    public Hello getJson(Hello hi) {
        logger.debug("hi = " + hi);
        return hi;
    }

    @RequestMapping(value = "/getXml", produces = {"application/xml;charset=UTF-8"})
    public Hello getXml(Hello hi) {
        logger.debug("hi = " + hi);
        return hi;
    }

    @RequestMapping(value = "/advice", produces = {"application/json;charset=UTF-8"})
    public String advice(@ModelAttribute("msg") String msg) {
        // 这里的入参msg是在SampleControllerAdvice中set进来的
        throw new IllegalArgumentException("SampleControllerAdvice：" + msg);
    }

    // 这是一个restcontroller，其实应该返回json，但是上面这样写是为了演示向jsp怎么setmessage。
    @ExceptionHandler(Exception.class)
    public String handleException(Exception e) {
        return "局部ExceptionHandler:"  + e.getMessage();
    }
    // 如果不是restcontroller而是jspview，可以像下面这样。下面演示演示了如何向jsp去setmessage。
//    @ExceptionHandler(Exception.class)
//    public ModelAndView handleException(Exception e) {
//        ModelAndView mav = new ModelAndView("error");
//        mav.addObject("errorMessage", "一些错误信息");
//        return mav;
//    }


    @RequestMapping(value = "/testInitBinder", produces = {"application/json;charset=UTF-8"})
    public ModelAndView testInitBinder(Hello hi) {
        ModelAndView mav = new ModelAndView("error");
        mav.addObject("errorMessage", "一些错误信息");
        return mav;
    }

    // InitBinder可以写在Controller里，也可以写在Advice里
    @InitBinder
    public void initBinder(WebDataBinder binder) {
//        binder.setRequiredFields("id"); // 打开后request时必须传id
//        binder.setDisallowedFields("name"); // 打开后request进来的时候就不会绑定name
    }


}
